const { Sequelize } = require("sequelize");
const { isRequired } = require("../utils");

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    "User",
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: Sequelize.UUIDV4,
        //是否允许为空
        allowNull: false,
        //是否为主键
        primaryKey: true,
        //备注
        comment: "用户id",
      },
      userName: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "用户姓名",
        validate: isRequired("用户姓名"),
      },
      account: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "账号",
        // 设置唯一不能重复
        unique: {
          msg: "账号已存在",
        },
        validate: isRequired("用户账号"),
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "密码",
        validate: isRequired("用户密码"),
      },
      gender: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "性别;0:女,1:男,2:保密",
        validate: {
          ...isRequired("性别"),
          isIn: {
            args: [[0, 1, 2]],
            msg: "性别信息输入错误",
          },
        },
      },
      mobile: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "手机号",
        // 设置唯一不能重复
        unique: {
          msg: "手机号已注册",
        },
        validate: {
          ...isRequired("手机号"),
          isMobilePhone: {
            args: ["zh-CN"],
            msg: "手机号格式错误",
          },
        },
      },
      avatar: {
        type: DataTypes.STRING,
        comment: "用户头像图片地址",
      },
    },
    {
      timestamps: true,
      tableName: "system_user",
      createdAt: "createTime",
      updatedAt: "updateTime",
      comment: "用户信息表",
    }
  );
  User.associate = (db) => {
    // 用户关联角色
    User.belongsToMany(db.Role, {
      through: db.UserRole,
      foreignKey: "userId",
      as: "roles",
    });
  };

  return User;
};
